package com.domino.server.persistence.playeraudit;

import java.util.logging.Logger;

import com.domino.server.user.FaceBookGraph;
import com.domino.shared.Player;
import com.domino.shared.PlayerId;

import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.MessageBuilder;
import com.google.appengine.api.xmpp.MessageType;
import com.google.appengine.api.xmpp.SendResponse;
import com.google.appengine.api.xmpp.SendResponse.Status;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;

public class PlayerAuditImpl implements PlayerAudit {

	Logger LOG = Logger.getLogger(getClass().getCanonicalName());

	private PlayerDao playerDao;
	private FaceBookGraph graph;

	public PlayerAuditImpl(PlayerDao playerDao, FaceBookGraph graph) {
		this.playerDao = playerDao;
		this.graph = graph;
	}

	@Override
	public void joinGame(Player player) {
		//LOG.warning("Audit player: " + player);

		/*if (player.getAccessToken() != null) {
			graph.resetBookmark(player.getAccessToken());
		}*/

		auditPlayer(player, new AuditOperation() {
			public void update(PlayerDO pdo) {
				pdo.incrementAccess();
			}
		});

		/*
		
		try {
			FacebookChatUtil.sendMessage("segersten", "hej");
			FacebookChatUtil.sendMessage("758377746", "hej");
		} catch (Exception e) {
			LOG.warning("Failed to chat: " + e.getMessage());
		}
		*/
	}

	@Override
	public void startPlayingWithBot(PlayerId playerId) {
		auditPlayerId(playerId, new AuditOperation() {
			
			@Override
			public void update(PlayerDO pdo) {
				pdo.incrementBotStart();
			}
		});
	}

	

	@Override
	public void startPlayingWithOpponent(PlayerId playerId) {
		auditPlayerId(playerId, new AuditOperation() {
			
			@Override
			public void update(PlayerDO pdo) {
				pdo.incrementOpponentStart();
			}
		});
	}

	@Override
	public void endPlayingWithOpponent(PlayerId playerId) {
		auditPlayerId(playerId, new AuditOperation() {
			
			@Override
			public void update(PlayerDO pdo) {
				pdo.incrementOpponentEnd();
			}
		});
	}
	

	@Override
	public void leaveGame(PlayerId playerId) {
		auditPlayerId(playerId, new AuditOperation() {
			
			@Override
			public void update(PlayerDO pdo) {
				pdo.incrementLeaveGame();
			}
		});
	}

	@Override
	public void endPlayingWithBot(PlayerId playerId) {
		auditPlayerId(playerId, new AuditOperation() {
			
			@Override
			public void update(PlayerDO pdo) {
				pdo.incrementBotEnd();
			}
		});
	}
	
	private void auditPlayer(Player player, AuditOperation auditOperation) {
		if (player.isAnonymous() == true) {
			player = createAnonymous();
		}
		try {
			PlayerDO pdo = playerDao.find(player.getId().getId());
			if (pdo == null) {
				pdo = new PlayerDO(player.getId().getId(), player.getNickname());
				auditOperation.update(pdo);
				playerDao.create(pdo);
				return;
			}
			auditOperation.update(pdo);
			playerDao.update(pdo);
		} catch (Exception e) {
			LOG.warning("Failed to log player " + player + " reasone:" + e.getMessage());
		}
	}
	
	private Player createAnonymous() {
		return new Player(new PlayerId("1"), "Anonymous", null);
	}

	private void auditPlayerId(PlayerId playerId, AuditOperation auditOperation) {
		if (playerId.getId().startsWith("A")) {
			playerId = createAnonymous().getId();
		}
		try {
			PlayerDO pdo = playerDao.find(playerId.getId());
			if (pdo == null) {
				LOG.severe("Could not find audit entry for playerId " + playerId);
				return;
			}
			auditOperation.update(pdo);
			playerDao.update(pdo);
		} catch (Exception e) {
			LOG.warning("Failed to log player " + playerId + " reasone:" + e.getMessage());
		}
	}

}

class FacebookChatUtil {
	
	static Logger LOG = Logger.getLogger(FacebookChatUtil.class.getCanonicalName());

	public static void sendMessage(String uid, String message) {
		JID jid = new JID(uid + "@chat.facebook.com");
        String msgBody = "Someone has sent you a gift. To view: http://example.com/gifts/";
        Message msg = new MessageBuilder()
            .withRecipientJids(jid)
            .withBody(msgBody)
            .build();
                
        boolean messageSent = false;
        XMPPService xmpp = XMPPServiceFactory.getXMPPService();
        if (xmpp.getPresence(jid).isAvailable() || true) {
            SendResponse status = xmpp.sendMessage(msg);
            Status jidStatus = status.getStatusMap().get(jid);
			messageSent = (jidStatus == SendResponse.Status.SUCCESS);
            if (messageSent) {
            	LOG.warning("Message sent to " + jid.getId());
            } else {
            	LOG.warning("Failure when message was sent " + jid.getId() + " error code: " + jidStatus);
            }
        } else {
        	LOG.warning("Message not sent, recipient not available: " + jid.getId());
        }
	}
	
}
